//
//  PKRequestManager.m
//  PianKe
//
//  Created by lanou on 15/9/26.
//  Copyright (c) 2015年 邓成成. All rights reserved.
//

#import "NWRequestManager.h"
#import <UIKit/UIKit.h>
@implementation NWRequestManager
+(void)requestWithType:(RequestType)type urlString:(NSString *)urlString
                parDic:(NSDictionary *)parDic finish:(RequestFinish)finish
                 error:(RequestError)xerror
{
    NWRequestManager *manager = [[NWRequestManager alloc]init];
    [manager requestWithType:type urlString:urlString parDic:parDic finish:finish error:xerror];
}


// 网络请求类：（封装方法）1.URL 2.POST/ GET 3：参数
- (void)requestWithType:(RequestType)type urlString:(NSString *)urlString
                 parDic:(NSDictionary *)parDic finish:(RequestFinish)finish
                  error:(RequestError)xerror
{
    // 拿到参数之后进行请求
    NSURL *url = [NSURL URLWithString:urlString];
    // 创建可变的URLRequest
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    //如果是请求方式是POST 需要设置参数和请求方式
    if (type == POST)
    {
        // 设置请求方式
        [request setHTTPMethod:@"POST"];
        if (parDic.count > 0)
        {
            NSData *data = [self parDicToDataWithDic:parDic];
            // 设置请求参数的Body体
            [request setHTTPBody:data];
        }
        
        
    }
  
        // IOS 9.0使用的有警告
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            if (data )
            {
                finish(data);
            }else{
                xerror(connectionError);
            }
        }];
 
    
    
   
    
    
}

// 将参数字典转化为POST请求所需要的参数体
- (NSData *)parDicToDataWithDic:(NSDictionary *)dic
{
    NSMutableArray *array = [NSMutableArray array];
    // 便历字典所得到每一个键  得到所以的key= value类型的字符串
    for (NSString *key in dic)
    {
        NSString *str = [NSString stringWithFormat:@"%@=%@",key, dic[key]];
        [array addObject:str];
    }
    // 数组里所有的key = value的字符串通过&符号链接
   NSString *parString = [array componentsJoinedByString:@"&"];
    return [parString dataUsingEncoding:NSUTF8StringEncoding];
}



@end
